package com.mazaiting.mybatisplus.config;


import com.mazaiting.mybatisplus.encrypt.plugins.MybatisDecryptionPlugin;
import com.mazaiting.mybatisplus.encrypt.plugins.MybatisEncryptionPlugin;
import com.mazaiting.mybatisplus.sensitive.plugins.MybatisSensitivePlugin;
import com.mazaiting.mybatisplus.service.IUserMetaObjectService;
import com.mazaiting.mybatisplus.service.impl.UserMetaObjectServiceImpl;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

/**
 * MybatisPlus配置类
 * 1. 提供加密插件: MybatisEncryptionPlugin
 * 2. 提供解密插件: MybatisDecryptionPlugin
 * 3. 提供脱敏插件: MybatisSensitivePlugin
 * @author danghailiang
 */
@Configuration
@EnableConfigurationProperties(MybatisCryptoProperties.class)
// Order(1) 率先启动，防止部分数据插入时为加载拦截器
@Order(1)
public class MyBatisAutoConfiguration {

    /**
     * 提供加密插件
     * @param properties 加解密配置数据
     * @return 加密插件
     */
    @Bean
    @ConditionalOnMissingBean(MybatisEncryptionPlugin.class)
    public MybatisEncryptionPlugin encryptionInterceptor(MybatisCryptoProperties properties) {
        return new MybatisEncryptionPlugin(properties.toMybatisCryptoConfig());
    }

    /**
     * 提供解密插件
     * @param properties 加解密配置数据
     * @return 解密插件
     */
    @Bean
    @ConditionalOnMissingBean(MybatisDecryptionPlugin.class)
    public MybatisDecryptionPlugin decryptionInterceptor(MybatisCryptoProperties properties) {
        return new MybatisDecryptionPlugin(properties.toMybatisCryptoConfig());
    }
    /**
     * 提供脱敏插件
     * @return 脱敏插件
     */
    @Bean
    @ConditionalOnMissingBean(MybatisSensitivePlugin.class)
    public MybatisSensitivePlugin mobileSensitivePlugin() {
        return new MybatisSensitivePlugin();
    }

    /**
     * 默认提供源数据服务
     * @return 源数据服务
     */
    @Bean
    @ConditionalOnMissingBean
    public IUserMetaObjectService userMetaObjectService() {
        return new UserMetaObjectServiceImpl();
    }
}
